import Taro from '@tarojs/taro';
import {goHomePage} from '@/utils';
import currentEnv from '../../configure/currentEnv';

const TAB_ROUTER = [
  // 首页
  '/pages/index/index',
  // 我的
  '/pages/mine/index/index',
];

function getUrl() {
  const pages = Taro.getCurrentPages();
  const beforePage = pages[pages.length - 2];

  if (!beforePage) {
    return;
  }

  const url = beforePage.route;
  const router = `/${url}`;
  const options = beforePage.options;

  // 拼接参数
  let urlWithArgs = url + '?';
  for (let key in options) {
    const value = options[key];
    urlWithArgs += key + '=' + value + '&';
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);

  return {
    router,
    url: `/${urlWithArgs}`,
  };
}

function loginBack() {
  const { router, url } = getUrl() ?? {};

  // h5 没switchTab, 直接跳转
  if (Taro.$isH5) {
    Taro.navigateBack();

    return;
  }

  // 没有路由, 返回首页
  if (!router) {
    Taro.reLaunch({
      url:currentEnv.project=='yingjing'?'/pages/index/index':'/pages/movie/index'
    })
    return;
  }

  // 如果是 switchTab 的路由, 要特殊处理
  if (TAB_ROUTER.includes(router)) {
    Taro.switchTab({ url });
  } else {
    Taro.navigateBack();
  }
}

export { loginBack };
